package cn.innosmart.aq.view.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.OrientationEventListener;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.tencent.android.tpush.XGPushConfig;
import com.tutk.IOTC.IMonitor;
import com.tutk.p2p.ConnectionEntity;
import com.tutk.p2p.ConnectionManager;
import com.tutk.p2p.IConnectionEntity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.BoxDetailMenuItemAdapter;
import cn.innosmart.aq.application.AQApplication;
import cn.innosmart.aq.bean.AlarmConditionBean;
import cn.innosmart.aq.bean.AquariumBean;
import cn.innosmart.aq.bean.BoxBean;
import cn.innosmart.aq.bean.DeviceBean;
import cn.innosmart.aq.bean.LvMenuItem;
import cn.innosmart.aq.bean.RuleBean;
import cn.innosmart.aq.camera.models.CameraBean;
import cn.innosmart.aq.customize.AlreadyInIncludingDialog;
import cn.innosmart.aq.customize.CustomsizeDialog;
import cn.innosmart.aq.customize.DetailLoadingDialog;
import cn.innosmart.aq.isp.ISPTool;
import cn.innosmart.aq.manager.CameraManager;
import cn.innosmart.aq.manager.DeviceManager;
import cn.innosmart.aq.manager.PlaceManager;
import cn.innosmart.aq.manager.RuleManager;
import cn.innosmart.aq.manager.SystemManager;
import cn.innosmart.aq.util.DeviceConstant;
import cn.innosmart.aq.util.SharedUtil;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.util.TimeZoneUntil;
import cn.innosmart.aq.view.activity.base.BaseActivity;
import cn.innosmart.aq.view.fragment.BoxDetailAllFragment;
import cn.innosmart.aq.view.fragment.BoxDetailAutoFragment;
import cn.innosmart.aq.view.fragment.BoxDetailCurrentFragment;
import cn.innosmart.aq.view.fragment.BoxDetailManagerFragment;
import cn.innosmart.aq.view.fragment.BoxDetailMoreFragment;

/**
 * Created by David on 2015/7/9.
 */
public class BoxDetailActivity extends BaseActivity implements ConnectionEntity.EventsCallback, ConnectionManager.onConnectInterface, IConnectionEntity {
    private static Handler mHandler;
    private final int HUBSET = 1;
    private final int RESET = 1;
    private final int UPDATESUCCESS = 2;
    private final int REBOOT = 3;
    private final int COUNTDOWN = 1001;
    private final int SWITCHCURRENTFRAGMENT = 1;
    private final int LEFTMENUITEMUPDATE = 2;
    private final int UPDATING = 17;
    private final int ALARM = 16;
    private final int REMOVEFAILED = 18;
    private final int ALARM_RECOMPUTER = 19;
    private final int RESULT_COUNT = 1001;
    public ConnectionEntity connectionEntity;
    private BoxBean currentBoxBean;
    private ImageView ivCurrent;
    private TextView tvCurrent;
    private ImageView ivAuto;
    private TextView tvAuto;
    private ImageView ivMore;
    private TextView tvMore;
    private LinearLayout bottomMenu;
    public AquariumBean aquariumBean;
    private LinearLayout currentColumn;
    private LinearLayout newsColumn;
    private LinearLayout autoColumn;
    private LinearLayout managerColumn;
    private TextView navUsername;
    private ImageView navHeadIcon;
    private int menuIndex = -1;
    private int lastIndex;
    private ListView id_lv_left_menu;
    private BoxDetailMenuItemAdapter menuItemAdapter;
    private RelativeLayout rlHeader;
    private List<LvMenuItem> mItems = new ArrayList<LvMenuItem>();
    /**
     * 设置界面Toolbar
     */
    private Toolbar toolbar;
    //设置Drawer
    private DrawerLayout mDrawer;
    private JSONArray preAddDeviceArray;
    private String preRemoveAddress;
    private CustomsizeDialog alarmDialog;
    private AlreadyInIncludingDialog abortModeDialog;
    private Button bt_positive;
    private TextView tv_content;
    private ArrayList<RuleBean> ruleBeans;
    private DetailLoadingDialog deviceDialog;
    private DetailLoadingDialog connectingDialog;
    private boolean isCancel = false;
    private CustomsizeDialog messageWaitingDialog;
    private CustomsizeDialog connectErrorDialog;
    private CameraBean currentCamera;
    //底部菜单栏的点击事件
    private View.OnClickListener mColumnOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            resetBottomMenuStatus(menuIndex);
            SystemConstant.currentAquariumBean = aquariumBean;
            switch (v.getId()) {
                case R.id.current_column:
                    //跳转到实时界面
                    switchCurrentFragment(aquariumBean);
                    break;
                case R.id.auto_column:
                    //跳转到自动控制界面
                    switchAutoFragment();
                    break;
                case R.id.more_column:
                    //跳转到更多界面
                    switchMoreFragment(aquariumBean);
                    break;
                case R.id.news_column:
                    Intent myIntent = new Intent(BoxDetailActivity.this, NewsActivity.class);
                    BoxDetailActivity.this.startActivity(myIntent);
                    break;
            }
        }
    };
    //左侧菜单的点击事件
    private View.OnClickListener mOnItemClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //企业版有多个鱼缸,所以左侧的菜单需要计算
            int position = (int) v.getTag();
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction tx = fm.beginTransaction();
            if (position == 0) {
                //高亮
                menuItemAdapter.setHighLightIndex(0);
                //重设底部菜单
                resetBottomMenuStatus(menuIndex);
//                    menuIndex = 0;
                //跳转到所有鱼缸列表界面
                switchAllFragment();
                //关闭左滑菜单
                mDrawer.closeDrawers();
            } else if (position < SystemConstant.aquariumList.size() + 1) {
                //高亮所选的鱼缸
                menuItemAdapter.setHighLightIndex(position);
                //重设底部菜单
                AquariumBean aqBean = SystemConstant.aquariumList.get(position - 1);
                SystemConstant.currentAquariumBean = aqBean;
                aquariumBean = aqBean;
                resetBottomMenuStatus(menuIndex);
                //跳转到鱼缸的相应界面
                switch (menuIndex) {
                    case -1:
                    case 0:
                        leftSwitchCurrentManger(fm, aqBean);
                        break;
                    case 1:
                        leftSwitchCurrentManger(fm, aqBean);
                        break;
                    case 2:
                        leftSwitchAutoManger(fm, aqBean);
                        break;
                    case 3:
                        leftSwitchMoreFragment(fm, aqBean);
                        break;
                    case 4:
                        leftSwitchManagerFragment(fm, aqBean);
                        break;
                }
                //关闭左滑菜单
                mDrawer.closeDrawers();
            } else if ((position - SystemConstant.aquariumList.size()) == 3) {
                //推送
                Intent intent = new Intent(BoxDetailActivity.this, PushMessageSettingAcitivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            } else if ((position - SystemConstant.aquariumList.size()) == 4) {
                //分享
                Intent intent = new Intent(BoxDetailActivity.this, ImageSelectActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            } else if ((position - SystemConstant.aquariumList.size()) == 5) {
                //控制中心设置
                Intent intent = new Intent(BoxDetailActivity.this, HubSettingActivity.class);
                startActivityForResult(intent, HUBSET);
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            }
        }
    };
    private IMonitor monitor = null;
    private boolean isFullScreen;


    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public static Handler getHandler() {
        return mHandler;
    }

    /**
     * 返回当前屏幕是否为竖屏。
     *
     * @param context
     * @return 当且仅当当前屏幕为竖屏时返回true, 否则返回false。
     */
    public static boolean isScreenOriatationPortrait(Context context) {
        return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    public CameraBean getCurrentCamera() {
        return currentCamera;
    }

    /**
     * 设置当前播放的摄像头
     *
     * @param object
     */
    public void setCurrentCamera(CameraBean object) {
        currentCamera = object;
    }

    /**
     * 设置横屏摄像头播放布局界面
     */
    public void setupViewInLandscapeLayout() {
        isFullScreen = true;
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        android.app.FragmentManager fm = getFragmentManager();
        android.app.FragmentTransaction tx = fm.beginTransaction();
        if (currentCamera != null && currentCamera.getView() != null) {
            tx.replace(R.id.camera, currentCamera.getView(), "Camera");
            tx.commit();
        }
    }


    public static void fixMinDrawerMargin(DrawerLayout drawerLayout) {
        try {
            Field f = DrawerLayout.class.getDeclaredField("mMinDrawerMargin");
            f.setAccessible(true);
            f.set(drawerLayout, 0);

            drawerLayout.requestLayout();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    OrientationEventListener orientationEventListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_boxdetail);

        orientationEventListener = new OrientationEventListener(this) {
            @Override
            public void onOrientationChanged(int orientation) {
                if (false && currentCamera != null) {
                    Display display = getWindowManager().getDefaultDisplay();
                    int width = display.getWidth();
                    int height = display.getHeight();
                    Toast.makeText(getApplicationContext(), "" + width + "," + height,
                            Toast.LENGTH_SHORT).show();
                    System.out.println("orientation:" + orientation);
                    if (orientation == 90 || orientation == 270) {
                        System.out.println("Landscape");
                        setupViewInLandscapeLayout();
                    } else {
                        System.out.println("Portrait");
                        setupViewInPortraitLayout();
                    }
                }
            }
        };
        orientationEventListener.enable();

        initView();

        //fixMinDrawerMargin((DrawerLayout)findViewById(R.id.drawer_layout));

        mHandler = new UiHandler();
        //初始化监听器
        initListener();
        Intent intent = getIntent();
        currentBoxBean = intent.getParcelableExtra("BoxBean");
        //初始化控件
        setDrawer();
        //设置菜单栏
        setBar(currentBoxBean);
        //设置左侧菜单
        setUpLeftMenu();
        //创建连接
        createConnect();
//      defaultSubcription();
        //清除报警消息 否则 10min还会报警
        changeIsp();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.

        initShopWeb();


    }

    /**
     * WebChromeClient subclass handles UI-related calls
     * Note: think chrome as in decoration, not the Chrome browser
     */
    public class GeoWebChromeClient extends WebChromeClient {
        @Override
        public void onGeolocationPermissionsShowPrompt(String origin,
                                                       GeolocationPermissions.Callback callback) {
            // Always grant permission since the app itself requires location
            // permission and the user has therefore already granted it
            callback.invoke(origin, true, false);
        }
    }

    WebView mShopWebView;

    public class GeoWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("taobao://")) {
                return false;
            }
            // When user clicks a hyperlink, load in the existing WebView
            view.loadUrl(url);
            return true;
        }
    }

    private GridView gview;
    private ArrayList<Map<String, Object>> data_list;
    private FishAdapter sim_adapter;
    private List<HashMap<String, FishGridViewItem>> hashMapList;

    private void initShopWeb() {

//        mShopWebView = (WebView) findViewById(R.id.webView1);
//        if (mShopWebView != null) {
//            // Brower niceties -- pinch / zoom, follow links in place
//            mShopWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
//            mShopWebView.getSettings().setBuiltInZoomControls(true);
//            mShopWebView.setWebViewClient(new GeoWebViewClient());
//            // Below required for geolocation
//            mShopWebView.getSettings().setJavaScriptEnabled(true);
//            mShopWebView.getSettings().setGeolocationEnabled(true);
//            mShopWebView.setWebChromeClient(new GeoWebChromeClient());
//            mShopWebView.loadUrl("https://item.taobao.com/item.htm?id=535539399731&qq-pf-to=pcqq.c2c");
//        }

        gview = (GridView) findViewById(R.id.flContent);

        hashMapList = new ArrayList<HashMap<String, FishGridViewItem>>();

        Point point = new Point();
        getWindowManager().getDefaultDisplay().getSize(point);

        sim_adapter = new FishAdapter(this, hashMapList, point.x / 2, point.y);

        //配置适配器
        gview.setAdapter(sim_adapter);

        final List<HashMap<String, FishGridViewItem>> hashMapListFinal = hashMapList;

//        TextView tvPrcing = (TextView)findViewById(R.id.tv_pricing);
//        tvPrcing.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                jumpFishPricing();
//            }
//        });

        gview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(BoxDetailActivity.this, FishDetailActivity.class);
                HashMap<String, FishGridViewItem> tempHashMap = hashMapListFinal.get(position);
                FishGridViewItem item = tempHashMap.get("item");
                intent.putExtra("title", item.title);
                intent.putExtra("url", item.url);
                intent.putExtra("thumbnail", item.thumbnail);

                startActivity(intent);
                overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
            }
        });

        getFishListData();

    }


    private void getFishListData() {
        StringRequest getBannerJsonRequest = new StringRequest("http://websitecdn.gangganghao.com.cn/AQImageList.json",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String jsonString = "{\"result\":" + response + "}";
                        System.out.println(jsonString);

                        try {
                            JSONObject o = new JSONObject(jsonString);
                            JSONArray arr = o.getJSONArray("result");
                            for (int i = 0; i < arr.length(); i++) {
                                HashMap<String, FishGridViewItem> tempHashMap = new HashMap<String, FishGridViewItem>();
                                JSONObject fishItem = arr.getJSONObject(i);
                                String thumbnail = fishItem.getString("thumbnail");
                                String url = fishItem.getString("image");
                                String title = fishItem.getString("title");
                                String name = fishItem.getString("name");
                                String type = fishItem.getString("type");
                                String desc = fishItem.getString("desc");
                                String contact = fishItem.getString("contact");
                                double price = fishItem.getDouble("price");
                                FishGridViewItem tempItem = new FishGridViewItem(thumbnail, url, title, name, type, desc, contact, price);
                                tempHashMap.put("item", tempItem);
                                hashMapList.add(tempHashMap);
                            }
                            sim_adapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                System.out.println("eror=" + error.toString());
            }
        });
        //设置5秒超时时间
        getBannerJsonRequest.setShouldCache(false);
        getBannerJsonRequest.setRetryPolicy(new DefaultRetryPolicy(0, 0, 1.0f));
        AQApplication.getInstance().mQueue.add(getBannerJsonRequest);
    }



    /**
     * 首次连接成功后默认订阅信鸽
     *
     * @deprecated
     */
    public void defaultSubcription() {
        SharedUtil.getInstance().readDefaultSubscription(connectionEntity.getUid());
        if (!SharedUtil.getInstance().readDefaultSubscription(connectionEntity.getUid())) {
            String xingeToken = XGPushConfig.getToken(getApplicationContext());
            if (xingeToken == null) {
                showToast(getString(R.string.activity_push_error));
                return;
            }
            ISPTool.getInstance().updateISP("xinge", connectionEntity.getUid(), "yes", "", xingeToken, new ISPTool.onISPCallBack() {
                @Override
                public void onSuccess(int resultcode, int xingeId) {
                    SharedUtil.getInstance().writeXinStatus(true, connectionEntity.getUid());
                }

                @Override
                public void onFailed(int resultcode, int xingeId) {
                }
            });
        }
    }

    /**
     * 初始化控件
     */
    private void initView() {
        currentColumn = (LinearLayout) findViewById(R.id.current_column);
        newsColumn = (LinearLayout) findViewById(R.id.news_column);
        autoColumn = (LinearLayout) findViewById(R.id.auto_column);
        managerColumn = (LinearLayout) findViewById(R.id.more_column);
        ivCurrent = (ImageView) findViewById(R.id.iv_current);
        tvCurrent = (TextView) findViewById(R.id.tv_current);
        ivAuto = (ImageView) findViewById(R.id.iv_auto);
        tvAuto = (TextView) findViewById(R.id.tv_auto);
        ivMore = (ImageView) findViewById(R.id.iv_more);
        tvMore = (TextView) findViewById(R.id.tv_more);
        bottomMenu = (LinearLayout) findViewById(R.id.bottom_menu);
    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        currentColumn.setOnClickListener(mColumnOnClickListener);
        newsColumn.setOnClickListener(mColumnOnClickListener);
        autoColumn.setOnClickListener(mColumnOnClickListener);
        managerColumn.setOnClickListener(mColumnOnClickListener);
    }

    /**
     * 重置底部菜单
     *
     * @param index 需要重置的position
     */
    private void resetBottomMenuStatus(int index) {
        switch (index) {
            case 1:
                ivCurrent.setColorFilter(null);
                tvCurrent.setTextColor(getResources().getColor(R.color.font_white));
                break;
            case 2:
                ivAuto.setColorFilter(null);
                tvAuto.setTextColor(getResources().getColor(R.color.font_white));
                break;
            case 3:
                ivMore.setColorFilter(null);
                tvMore.setTextColor(getResources().getColor(R.color.font_white));
                break;
            case 4:
                ivMore.setColorFilter(null);
                tvMore.setTextColor(getResources().getColor(R.color.font_white));
                break;
        }
    }

    /**
     * 设置默认Fragment
     */
    private void setDefaultFragment() {
//        if (SystemConstant.MODE == SystemConstant.PERSONALMODE) {
//            //个人版跳转到实时界面
//            for (int i = 0; i < SystemConstant.aquariumList.size(); i++) {
//                //SN0521_AAAAAAAAAAAAAAAAAAAA默认鱼缸
//                if ("SN0521_AAAAAAAAAAAAAAAAAAAA".equals(SystemConstant.aquariumList.get(i).getId())) {
//                    SystemConstant.currentAquariumBean = SystemConstant.aquariumList.get(i);
//                    aquariumBean = SystemConstant.currentAquariumBean;
//                }
//            }
//            switchCurrentFragment(aquariumBean);
//        } else if (SystemConstant.MODE == SystemConstant.COMPANYMODE) {
//            //企业版跳转到所有鱼缸界面
        switchAllFragment();
//        }
    }

    /**
     * 跳转到所有设备Fragment
     */
    private void switchAllFragment() {
        if (menuIndex != 0) {
            lastIndex = menuIndex;
//            menuIndex = 0;
            bottomMenu.setVisibility(View.GONE);
            BoxDetailAllFragment fragment;
            FragmentManager fm = getSupportFragmentManager();
            fragment = (BoxDetailAllFragment) fm.findFragmentByTag("All");
            if (fragment == null) {
                fragment = new BoxDetailAllFragment();
            }
            fragment.setConnectionEntity(connectionEntity);
            FragmentTransaction tx = fm.beginTransaction();
            tx.replace(R.id.boxdetail_content, fragment, "All");
            tx.commitAllowingStateLoss();
        }
    }

    //跳转到实时界面
    public void switchCurrentFragment(AquariumBean aquariumBean) {
        this.aquariumBean = aquariumBean;
        bottomMenu.setVisibility(View.VISIBLE);
        lastIndex = menuIndex;
        menuIndex = 1;
        findViewById(R.id.nearbyTextView).setVisibility(View.VISIBLE);
        findViewById(R.id.nearbyTextView).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(BoxDetailActivity.this, NearbyActivity.class);
                BoxDetailActivity.this.startActivity(myIntent);
            }
        });

        ivCurrent.setColorFilter(getResources().getColor(R.color.font_lightblue));
        tvCurrent.setTextColor(getResources().getColor(R.color.font_lightblue));
        BoxDetailCurrentFragment fragment;
        FragmentManager fm = getSupportFragmentManager();
        fragment = (BoxDetailCurrentFragment) fm.findFragmentByTag("Current");
        if (fragment == null) {
            fragment = new BoxDetailCurrentFragment();
        }
        fragment.setConnectionEntity(connectionEntity);
        //set current aquarium
        fragment.setAquarium(aquariumBean);
        if (currentCamera != null) {
            fragment.setCurrentCamera(currentCamera);
        }
        FragmentTransaction tx = fm.beginTransaction();
        tx.replace(R.id.boxdetail_content, fragment, "Current");
        tx.commitAllowingStateLoss();

        ((ImageView) findViewById(R.id.iv_headicon)).setVisibility(View.VISIBLE);

    }

    //跳转到自动控制界面
    private void switchAutoFragment() {
        bottomMenu.setVisibility(View.VISIBLE);
        lastIndex = menuIndex;
        menuIndex = 2;
        findViewById(R.id.nearbyTextView).setVisibility(View.GONE);
        ivAuto.setColorFilter(getResources().getColor(R.color.font_lightblue));
        tvAuto.setTextColor(getResources().getColor(R.color.font_lightblue));
        BoxDetailAutoFragment fragment;
        FragmentManager fm = getSupportFragmentManager();
        fragment = (BoxDetailAutoFragment) fm.findFragmentByTag("Auto");
        if (fragment == null) {
            fragment = new BoxDetailAutoFragment();
        }
        fragment.setConnectionEntity(connectionEntity);
        fragment.setAquarium(aquariumBean);
        FragmentTransaction tx = fm.beginTransaction();
        tx.replace(R.id.boxdetail_content, fragment, "Auto");
        tx.commit();

        ((ImageView) findViewById(R.id.iv_headicon)).setVisibility(View.GONE);

    }


    //跳转到更多界面
    private void switchMoreFragment(AquariumBean aquariumBean) {
        bottomMenu.setVisibility(View.VISIBLE);
        lastIndex = menuIndex;
        menuIndex = 3;

        findViewById(R.id.nearbyTextView).setVisibility(View.GONE);

        ivMore.setColorFilter(getResources().getColor(R.color.font_lightblue));
        tvMore.setTextColor(getResources().getColor(R.color.font_lightblue));
        BoxDetailMoreFragment fragment;
        FragmentManager fm = getSupportFragmentManager();
        fragment = (BoxDetailMoreFragment) fm.findFragmentByTag("More");
        if (fragment == null) {
            fragment = new BoxDetailMoreFragment();
        }
        fragment.setConnectionEntity(connectionEntity);
        fragment.setAquarium(aquariumBean);
        FragmentTransaction tx = fm.beginTransaction();
        tx.replace(R.id.boxdetail_content, fragment, "More");
        tx.commit();

        ((ImageView) findViewById(R.id.iv_headicon)).setVisibility(View.GONE);

    }

    //跳转到设备管理界面
    public void switchManagerFragment() {
        lastIndex = menuIndex;
        menuIndex = 4;
        BoxDetailManagerFragment fragment;
        FragmentManager fm = getSupportFragmentManager();
        fragment = (BoxDetailManagerFragment) fm.findFragmentByTag("Manager");
        if (fragment == null) {
            fragment = new BoxDetailManagerFragment();
        }
        fragment.setConnectionEntity(connectionEntity);
        fragment.setAquarium(SystemConstant.currentAquariumBean);
        FragmentTransaction tx = fm.beginTransaction();
        tx.replace(R.id.boxdetail_content, fragment, "Manager");
        tx.commit();

        ((ImageView) findViewById(R.id.iv_headicon)).setVisibility(View.GONE);

    }

    /**
     * 初始化并设置左侧菜单
     */
    private void setUpLeftMenu() {
        LayoutInflater inflater = LayoutInflater.from(this);
        rlHeader = (RelativeLayout) findViewById(R.id.rl_header);
//        if (SystemConstant.MODE == SystemConstant.PERSONALMODE) {
//            TextView tvAquariumTitle = (TextView) findViewById(R.id.tv_aquarium_title);
//            tvAquariumTitle.setVisibility(View.GONE);
//        }
        id_lv_left_menu = (ListView) findViewById(R.id.left_menu);
        menuItemAdapter = new BoxDetailMenuItemAdapter(this, mItems);
        id_lv_left_menu.setAdapter(menuItemAdapter);
        menuItemAdapter.setHighLightIndex(0);
        menuItemAdapter.setOnClickListener(mOnItemClickListener);
        navUsername = (TextView) findViewById(R.id.nav_username);
        navHeadIcon = (ImageView) findViewById(R.id.nav_headIcon);
        rlHeader.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawer.closeDrawers();
                leftMenuHeaderClicked();
            }
        });
        navUsername.setText(SystemConstant.nickname);
        toolbar.setNavigationIcon(R.drawable.ic_menu);
    }

    /**
     * 左侧头像点击事件
     */
    private void leftMenuHeaderClicked() {
        Intent intent = new Intent(BoxDetailActivity.this, CountSettingActivity.class);
        startActivityForResult(intent, RESULT_COUNT);
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == HUBSET && resultCode == RESET) {
            loadingDialog();
        } else if (requestCode == HUBSET && resultCode == UPDATESUCCESS) {

        } else if (requestCode == RESULT_COUNT && resultCode == RESULT_OK) {
            System.gc();
            connectionEntity.isConnect = false;
            DeviceConstant.alarmConditionBeanHashMap.clear();
            SystemConstant.aquariumList = null;
            SystemConstant.ruleList = null;
            SystemConstant.sceneList = null;
            SystemConstant.scheduleList = null;
            SystemConstant.currentAquariumBean = null;
            SystemConstant.excludedCount = 0;
            exit();
        }
    }

    //左侧菜单跳转到自动控制界面
    private void leftSwitchAutoManger(FragmentManager fm, AquariumBean aquariumBean) {
        ivAuto.setColorFilter(getResources().getColor(R.color.font_lightblue));
        tvAuto.setTextColor(getResources().getColor(R.color.font_lightblue));
        BoxDetailAutoFragment allFragment;
        allFragment = (BoxDetailAutoFragment) fm.findFragmentByTag("Auto");
        if (allFragment != null && menuIndex == 2) {
            allFragment.setAquarium(aquariumBean);
            allFragment.onResume();
        } else {
            switchAutoFragment();
        }
    }

    /**
     * 左侧菜单跳转到实时界面
     *
     * @param fm
     * @param aquariumBean
     */
    private void leftSwitchCurrentManger(FragmentManager fm, AquariumBean aquariumBean) {
        ivCurrent.setColorFilter(getResources().getColor(R.color.font_lightblue));
        tvCurrent.setTextColor(getResources().getColor(R.color.font_lightblue));
        BoxDetailCurrentFragment currentFragment;
        currentFragment = (BoxDetailCurrentFragment) fm.findFragmentByTag("Current");
        if (currentFragment != null && menuIndex == 1) {
            currentFragment.setAquarium(aquariumBean);
            currentFragment.onResume();
        } else {
            switchCurrentFragment(aquariumBean);
        }
    }

    /**
     * 左侧菜单跳转到设备管理界面
     *
     * @param fm
     * @param aquariumBean
     */
    private void leftSwitchManagerFragment(FragmentManager fm, AquariumBean aquariumBean) {
        ivMore.setColorFilter(getResources().getColor(R.color.font_lightblue));
        tvMore.setTextColor(getResources().getColor(R.color.font_lightblue));
        BoxDetailManagerFragment managerFragment;
        managerFragment = (BoxDetailManagerFragment) fm.findFragmentByTag("Manager");
        if (managerFragment != null && menuIndex == 4) {
            managerFragment.setAquarium(aquariumBean);
            managerFragment.onResume();
        } else {
            switchManagerFragment();
        }
    }

    /**
     * 左侧菜单跳转到更多界面
     *
     * @param fm
     * @param aquariumBean
     */
    private void leftSwitchMoreFragment(FragmentManager fm, AquariumBean aquariumBean) {
        ivMore.setColorFilter(getResources().getColor(R.color.font_lightblue));
        tvMore.setTextColor(getResources().getColor(R.color.font_lightblue));
        BoxDetailMoreFragment moreFragment;
        moreFragment = (BoxDetailMoreFragment) fm.findFragmentByTag("More");
        if (moreFragment != null && menuIndex == 3) {
            moreFragment.setAquarium(aquariumBean);
            moreFragment.onResume();
        } else {
            switchMoreFragment(aquariumBean);
        }
    }

    //设置顶部Toolbar
    private void setBar(BoxBean boxbean) {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("");
        TextView tv = (TextView) toolbar.findViewById(R.id.tv_toolbar);
        ((ImageView) findViewById(R.id.iv_headicon)).setImageResource(R.drawable.ic_menu);
        ((ImageView) findViewById(R.id.iv_headicon)).setVisibility(View.VISIBLE);

        tv.setText(boxbean.getTitle());
        setSupportActionBar(toolbar);

//        toolbar.setOnMenuItemClickListener(onMenuItemClick);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawer.openDrawer(GravityCompat.START);
            }
        });

    }


    private void setDrawer() {
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    }

    //创建连接
    private void createConnect() {
        showConnectDialog(BoxDetailActivity.this, getString(R.string.connecting));
        String uid = currentBoxBean.getUid();
        String username = currentBoxBean.getUsername();
        String password = currentBoxBean.getPassword();
        ConnectionManager.getInstance().setOnConnectCallBack(this);
        connectionEntity = ConnectionManager.getInstance().createConnect(getApplicationContext(), uid, username, password, this);
        connectionEntity.setEventsCallback(this);
    }

    @Override
    protected void onResume() {
        //强制竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        menuItemAdapter.creatAquariumMenu();
        setBaseDialogContext(this);
        super.onResume();
        toolbar.setNavigationIcon(null);
    }

    /**
     * 清除报警标志
     */
    public void changeIsp() {
        ArrayList<String> uids = new ArrayList<>();
        if (SystemConstant.boxBeanList != null)
            for (BoxBean boxBean : SystemConstant.boxBeanList) {
                uids.add(boxBean.getUid());
            }
        ISPTool.getInstance().changeEvent(uids, 0);
    }

    /**
     * 设置竖屏布局界面, 全屏后恢复竖屏
     */
    private void setupViewInPortraitLayout() {
        isFullScreen = false;
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//        setContentView(R.layout.camera_landscape);
        android.app.FragmentManager fm = getFragmentManager();
        android.app.FragmentTransaction tx = fm.beginTransaction();
        if (currentCamera != null && currentCamera.getView() != null) {
            tx.remove(fm.findFragmentByTag("Camera"));
//            tx.replace(R.id.camera, currentCamera.getView(), "Camera");
            tx.commit();
            getSupportFragmentManager().findFragmentByTag("Current").onResume();
        }
    }

    @Override
    public void onBackPressed() {
        if (!isScreenOriatationPortrait(this)) {
            setupViewInPortraitLayout();
            return;
        }
        //如果菜单打开先关闭菜单
        if (mDrawer.isDrawerOpen(GravityCompat.START)) {
            mDrawer.closeDrawers();
            return;
        }
//        if (SystemConstant.MODE == SystemConstant.PERSONALMODE) {
        if (false) {
            //个人模式  如果处于设备管理界面 先跳转到更多界面
            if (menuIndex == 4) {
                switchMoreFragment(aquariumBean);
            } else {
                //断开连接
                System.gc();
                connectionEntity.isConnect = false;
                if (DeviceConstant.alarmConditionBeanHashMap != null)
                    DeviceConstant.alarmConditionBeanHashMap.clear();
                SystemConstant.aquariumList = null;
                SystemConstant.ruleList = null;
                SystemConstant.sceneList = null;
                SystemConstant.scheduleList = null;
                SystemConstant.currentAquariumBean = null;
                SystemConstant.excludedCount = 0;
                exit();
            }
        } else {
            //企业模式  如果处于设备管理界面 先跳转到更多界面
            if (menuIndex == 4) {
                switchMoreFragment(aquariumBean);
            } else if (menuIndex == 0 || menuIndex == -1) {
                System.gc();
                connectionEntity.isConnect = false;
                DeviceConstant.alarmConditionBeanHashMap.clear();
                SystemConstant.aquariumList = null;
                SystemConstant.ruleList = null;
                SystemConstant.sceneList = null;
                SystemConstant.scheduleList = null;
                SystemConstant.currentAquariumBean = null;
                SystemConstant.excludedCount = 0;
                exit();
            } else {
                //优先跳转到所有鱼缸列表界面
                resetBottomMenuStatus(menuIndex);
                menuItemAdapter.setHighLightIndex(0);
                switchAllFragment();
                menuIndex = 0;
                findViewById(R.id.nearbyTextView).setVisibility(View.GONE);
            }
        }
    }

    //退出
    @Override
    public void exit() {
        Intent intent = new Intent(BoxDetailActivity.this, BoxListActivity.class);
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    //连接状态回掉函数
    @Override
    public void onConnectStatus(String did, int sessionId, int status) {
        changeConnectDialog(BoxDetailActivity.this, getString(R.string.connecting));
        Message msg = mHandler.obtainMessage();
        msg.what = status;
        msg.obj = "did=" + did + ",sessinId=" + sessionId + ",status=" + status;
        mHandler.sendMessage(msg);
    }

    public void disConnect() {
        connectionEntity.disConnect();
    }

    @Override
    public void onBoxMessageAllOver(int ret) {
        connectionEntity.isConnect = true;
//        mHandler.sendEmptyMessage(0);
    }

    @Override
    public void onBoxMessageOver(int ret, String flag, Object object) {
        if (flag.equals(connectionEntity.PLACELIST)) {
            //获取所有Place信息的回调
            if (ret == 0) {
                mHandler.sendEmptyMessage(2);
            }
        } else if (flag.equals(connectionEntity.DEVICEINCLUDE)) {
            if (ret == -1) {
                //对话框提示已经进入including模式
                mHandler.sendEmptyMessage(5);
            }
        } else if (flag.equals(connectionEntity.DEVICEUPDATE)) {
            //添加设备的消息回调
            if (ret == 0) {
                if (SystemConstant.isIncluding) {
                    SystemConstant.includingDeviceNum = SystemConstant.includingDeviceNum - 1;
                    if (SystemConstant.includingDeviceNum == 0) {
                        mHandler.sendEmptyMessage(6);
                    }
                }
            }
        } else if (flag.equals(connectionEntity.DEVICEEXCLUDE)) {
            if (ret == -1) {
                //对话框提示已经进入excluding模式
                mHandler.sendEmptyMessage(5);
            }
        }
    }

    /**
     * {"type":"notif","name":"gateway.modeChanged","data":{"mode":"abort"},"source":"device_ZWaveHandler"}
     * <p>
     * 删除设备的状态
     * {"type":"notif","name":"gateway.modeChanged","data":{"mode":"excluding"},"source":"device_ZWaveHandler"}
     * {"type":"notif","name":"gateway.modeChanged","data":{"mode":"normal"},"source":"device_ZWaveHandler"}
     * {"type":"notif","name":"gateway.modeChanged","data":{"mode":"excluded"},"source":"device_ZWaveHandler"}
     * {"name":"GATEWAY.deviceExcluded","type":"notif","data":{"addresses":["zwave://e5ad378b/26/"]},"source":"device_ZWaveHandler"}
     * {"type":"notif","name":"DeviceManager.deviceUpdated","data":{"timestamp":"1438247795","id":"","operate":"Excluded"}}
     * <p>
     * 添加设备状态
     * {"type":"notif","name":"gateway.modeChanged","data":{"mode":"including"},"source":"device_ZWaveHandler"}
     * {"type":"notif","name":"gateway.modeChanged","data":{"mode":"querying"},"source":"device_ZWaveHandler"}
     * {"name":"gateway.deviceExcluded","type":"notif","data":{"addresses":["zwave://e5ad378b/27/"]},"source":"device_ZWaveHandler"}
     * {"type":"notif","name":"gateway.deviceIncluded","data":{"nif":{"nodeid":27,"manufacturerid":"5254"},"channels":[{"address":"zwave://e5ad378b/27/49/1/1","name":"Air Temperature","devicetype":"ZXT-120","functype":11,"label":"Air Temperature"},{"address":"zwave://e5ad378b/27/64/1/0","name":"Mode","devicetype":"ZXT-120","functype":37,"label":"Mode"},{"address":"zwave://e5ad378b/27/67/1/1","name":"Heating 1","devicetype":"ZXT-120","functype":39,"label":"Heating 1"},{"address":"zwave://e5ad378b/27/67/1/2","name":"Cooling 1","devicetype":"ZXT-120","functype":39,"label":"Cooling 1"},{"address":"zwave://e5ad378b/27/67/1/4","name":"Unused 4","devicetype":"ZXT-120","functype":39,"label":"Unused 4"},{"address":"zwave://e5ad378b/27/68/1/0","name":"Fan Mode","devicetype":"ZXT-120","functype":38,"label":"Fan Mode"},{"address":"zwave://e5ad378b/27/112/1/25","name":"Indicate a location for IR code  learning and start learning","devicetype":"ZXT-120","functype":32,"label":"Indicate a location for IR code  learning and start learning"},{"address":"zwave://e5ad378b/27/112/1/26","name":"Learning status register","devicetype":"ZXT-120","functype":32,"label":"Learning status register"},{"address":"zwave://e5ad378b/27/112/1/27","name":"IR code number for built-in  code library","devicetype":"ZXT-120","functype":32,"label":"IR code number for built-in  code olibrary"},{"address":"zwave://e5ad378b/27/112/1/28","name":"External IR Emitter power  level","devicetype":"ZXT-120","functype":32,"label":"External IR Emitter power  level"},{"address":"zwave://e5ad378b/27/112/1/32","name":"Surround IR control","devicetype":"ZXT-120","functype":32,"label":"Surround IR control"},{"address":"zwave://e5ad378b/27/112/1/33","name":"Surround IR control","devicetype":"ZXT-120","functype":32,"label":"Surround IR control"},{"address":"zwave://e5ad378b/27/128/1/0","name":"Battery Level","devicetype":"ZXT-120","functype":36,"label":"Battery Level"}]},"source":"device_ZWaveHandler"}
     * {"type":"notif","name":"DeviceManager.deviceUpdated","data":{"timestamp":"1438247876","id":"","operate":"Included"}}
     * <p>
     * <p>
     * {"type":"notif","name":"gateway.modeChanged","data":{"mode":"including"},"source":"device_ZWaveHandler"}
     * {"type":"notif","name":"gateway.modeChanged","data":{"mode":"querying"},"source":"device_ZWaveHandler"}
     * {"name":"gateway.deviceExcluded","type":"notif","data":{"addresses":["zwave://e5ad378b/28/"]},"source":"device_ZWaveHandler"}
     * {"type":"notif","name":"gateway.deviceIncluded","data":{"nif":{"nodeid":27,"man***********************
     * {"type":"notif","name":"DeviceManager.deviceUpdated","data":{"timestamp":"1438248066","id":"","operate":"Included"}}
     * 添加到一半退出
     * <p>
     * /
     * <p>
     * <p>
     * /**
     *
     * @param UID
     * @param eventType
     * @param message
     */
    @Override
    public void onEventsCallback(String UID, int eventType, String message) {
        if (UID.equals(connectionEntity.getUid())) {
            switch (eventType) {
                case SystemConstant.EVENT_ID_GATEWAY_MODECHANGED:
                    //模式改变的通知
                    if (SystemConstant.isIncluding) {
                        //  在添加模式下
                        try {
                            JSONObject jsonObject = new JSONObject(message);
                            JSONObject data = jsonObject.getJSONObject("data");
                            String mode = data.getString("mode");
                            if (mode.equals("including")) {
                                mHandler.sendEmptyMessage(3);
                            } else if (mode.equals("querying")) {
                                //关掉倒计时对话框
                                deviceDialog.closeTimer();
                                mHandler.sendEmptyMessage(4);
                            } else if (mode.equals("abort")) {
                                //退出添加删除模式
                                if (abortModeDialog != null) {
                                    abortModeDialog.dismiss();
                                }
                                SystemConstant.isIncluding = false;
                                SystemConstant.includingDeviceNum = 0;
                                SystemConstant.excludedCount = 0;
                                SystemConstant.isExcluding = false;
                            } else if (mode.equals("excluding")) {
                                //添加状态下，先删除该设备
                                mHandler.sendEmptyMessage(3);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else if (SystemConstant.isExcluding) {
                        //在删除模式下
                        try {
                            JSONObject jsonObject = new JSONObject(message);
                            JSONObject data = jsonObject.getJSONObject("data");
                            String mode = data.getString("mode");
                            if (mode.equals("abort")) {
                                //退出添加删除模式
                                if (abortModeDialog != null) {
                                    abortModeDialog.dismiss();
                                }
                            } else if (mode.equals("excluding")) {
                                //开始删除
                                mHandler.sendEmptyMessage(3);
                            } else if (mode.equals("excluded")) {
                                //删除成功
                                mHandler.sendEmptyMessage(4);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                //数据上报处理
                case SystemConstant.EVENT_ID_CHANNEL_SENSORVALUEUPDATED:
                    System.out.println("EVENT_ID_CHANNEL_SENSORVALUEUPDATED");

                    Intent intent = new Intent();
                    intent.setAction("connect_event_online");
                    sendBroadcast(intent);

                    //如果没有设备数据，则直接返回
                    if (SystemConstant.deviceBeanHashMap == null) {
                        return;
                    }
                    //解析上报的数据
                    try {
                        JSONObject jsonObject = new JSONObject(message);
//                        logV(jsonObject.toString());
                        JSONObject data = jsonObject.getJSONObject("data");
                        JSONArray channels = data.getJSONArray("channels");
                        JSONObject device = channels.getJSONObject(0);
                        String address = device.getString("address");
                        int senserunity = device.getInt("sensorunit");
                        Double sensorvalue = device.getDouble("sensorvalue");
                        //根据Address找到相应设备对象
                        DeviceBean deviceBean = SystemConstant.deviceBeanHashMap.get(address);
                        //更新内存数据
                        if (deviceBean != null) {
                            if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_SWITCH) {
                                String slist[] = deviceBean.getAddress().split("\\/");
                                String wattDeviceBeanAddress = slist[0] + "//" + slist[2] + "/" + slist[3] + "/" + 50 + "/" + slist[5] + "/" + 2; // zwave://e5a00bee/3/50/3/2
                                DeviceBean wattDeviceBean = SystemConstant.deviceBeanHashMap.get(wattDeviceBeanAddress);
                                if (wattDeviceBean != null)
                                    mHandler.removeMessages(ALARM_RECOMPUTER, wattDeviceBean);
                            }
                            deviceBean.setSensorvalue(sensorvalue);
                        }
                        //根据Type判断水位Sensor是否报警
                        if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_WATERLEVER) {
                            if (sensorvalue != 0) {
                                deviceBean.setAlarm(true);
                            } else {
                                deviceBean.setAlarm(false);
                            }
                        }
                        try {
                            //查找是否设置警戒范围
                            AlarmConditionBean alarmConditionBean = DeviceConstant.alarmConditionBeanHashMap.get(deviceBean.getAddress());
                            //如果找到，则进行值比较，+-1范围内是异常黄色报警，>+-2范围是红色报警
                            if (alarmConditionBean != null) {
                                double above = alarmConditionBean.getAboveValue();
                                double below = alarmConditionBean.getBelowValue();
                                if (sensorvalue < above || sensorvalue > below) {
                                    deviceBean.setAlarm(true);
                                    if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_PH) {
                                        //diff value 1
                                        if ((sensorvalue + 10) < above || (sensorvalue - 10) > below) {
                                            deviceBean.setDeepAlarm(true); //红色Alarm, -> DeepAlarm
                                        } else {
                                            deviceBean.setDeepAlarm(false);
                                        }

                                        String aquariumid = deviceBean.getPlace();
                                        Message msg = mHandler.obtainMessage();
                                        msg.what = ALARM;
                                        msg.obj = deviceBean;
                                        mHandler.sendMessage(msg);

                                    } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_TEMPERATURE) {
                                        if ((sensorvalue + 20) < above || (sensorvalue - 20) > below) {
                                            deviceBean.setDeepAlarm(true);
                                        } else {
                                            deviceBean.setDeepAlarm(false);
                                        }

                                        String aquariumid = deviceBean.getPlace();
                                        Message msg = mHandler.obtainMessage();
                                        msg.what = ALARM;
                                        msg.obj = deviceBean;
                                        mHandler.sendMessage(msg);
                                    } else if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_METER_WATT) {
                                        if (true || sensorvalue < 10) {
//                                            Message msg = mHandler.obtainMessage();
//                                            msg.what = ALARM;
//                                            msg.obj = deviceBean;
//                                            mHandler.sendMessage(msg);

                                            {
                                                mHandler.removeMessages(ALARM_RECOMPUTER, deviceBean);
                                                Message msg2 = mHandler.obtainMessage();
                                                msg2.what = ALARM_RECOMPUTER;
                                                msg2.obj = deviceBean;
                                                mHandler.sendMessageDelayed(msg2, 5000);
                                            }
                                        }
                                    }

                                } else {
                                    deviceBean.setAlarm(false); //黄色
                                    deviceBean.setDeepAlarm(false);
                                }
                            } else {
                                //没有设置警戒范围 ，清除报警
                                deviceBean.setAlarm(false);
                                deviceBean.setDeepAlarm(false);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        //判断是否在实时界面，在就更新数据
                        if (menuIndex == 1) {
                            mHandler.sendEmptyMessage(8); //实时
                        } else if (menuIndex == 0) {
                            mHandler.sendEmptyMessage(9); //所有鱼缸界面
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                //删除设备通知
                case SystemConstant.EVENT_ID_GATEWAY_DEVICEEXCLUDED:
                    try {
                        JSONObject jsonObject = new JSONObject(message);
                        JSONObject data = jsonObject.getJSONObject("data");
                        preRemoveAddress = data.getJSONArray("addresses").get(0).toString();
                        ArrayList<String> addresses = aquariumBean.getDeivices();
                        boolean isExist = false;
                        for (int i = 0; i < addresses.size(); i++) {
                            if (addresses.get(i).contains(preRemoveAddress)) {
                                isExist = true;
                                break;
                            }
                        }

                        //检查删除的设备是否为有效设备，有效：非1
                        boolean removeInvalidDevice = false;
                        {
                            String[] l = preRemoveAddress.replace("zwave://", "").split("/");
                            if (!l[1].equals("1")) {
                                removeInvalidDevice = true;
                            }
                        }

                        if (!isExist) {
                            if (removeInvalidDevice) {
                                if (SystemConstant.isIncluding && SystemConstant.excludedCount == 0) {
                                    mHandler.sendEmptyMessage(14);
                                    mHandler.sendEmptyMessageDelayed(13, 3000);
                                    SystemConstant.excludedCount++;
                                }
                                if (SystemConstant.isExcluding) {
                                    BoxDetailManagerFragment fragment;
                                    FragmentManager fm = getSupportFragmentManager();
                                    fragment = (BoxDetailManagerFragment) fm.findFragmentByTag("Manager");
                                    fragment.hideLoadingDialog();
                                    mHandler.sendEmptyMessage(12);
                                    SystemConstant.isExcluding = false;
                                }
                            } else {
                                SystemConstant.isExcluding = false;
                                SystemConstant.isIncluding = false;
                            }
                        } else {
                            if (SystemConstant.isIncluding && SystemConstant.excludedCount == 0) {
                                mHandler.sendEmptyMessage(14);
                                SystemConstant.excludedCount++;
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case SystemConstant.EVENT_ID_GATEWAY_DEVICEINCLUDED:
                    //ZWAVEHandler添加设备成功
                    if (SystemConstant.isIncluding) {
                        try {
                            JSONObject jsonObject = new JSONObject(message);
                            JSONObject data = jsonObject.getJSONObject("data");
                            JSONArray jsonDevices = data.getJSONArray("channels");
                            preAddDeviceArray = jsonDevices;
                            //记录预添加设备的device信息
                            for (int i = 0; i < preAddDeviceArray.length(); i++) {
                                int devicetype = preAddDeviceArray.getJSONObject(i).getInt("functype");
                                if (devicetype == DeviceConstant.FUNCTYPE_FEEDER || devicetype == DeviceConstant.FUNCTYPE_SWITCH || devicetype == DeviceConstant.FUNCTYPE_PH || devicetype == DeviceConstant.FUNCTYPE_TEMPERATURE || devicetype == DeviceConstant.FUNCTYPE_WATERLEVER) {
                                    SystemConstant.includingDeviceNum++;
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case SystemConstant.EVENT_ID_DEVICE_UPDATED:
                    //{"type":"notif","name":"DeviceManager.deviceUpdated","data":{"timestamp":"1438313064","id":"","operate":"Included"}}
                    //底层数据保存成功。
                    try {
                        JSONObject jsonObject = new JSONObject(message);
                        JSONObject data = jsonObject.getJSONObject("data");
                        String operate = data.getString("operate");
                        if ("Included".equals(operate) && SystemConstant.isIncluding) {
                            //添加模式中
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    //Update之前预添加设备的device信息，将鱼缸信息加入设备中
                                    for (int i = 0; i < preAddDeviceArray.length(); i++) {
                                        try {
                                            final DeviceBean deviceBean = new DeviceBean(preAddDeviceArray.getJSONObject(i));
                                            SystemConstant.deviceBeanHashMap.put(deviceBean.getAddress(), deviceBean);
//                                      // 准备参数
                                            final JSONObject jParams = new JSONObject();
                                            String name = DeviceConstant.nameMap.get(deviceBean.getName());
                                            if (TextUtils.isEmpty(name)) {
                                            } else {
                                                jParams.put("name", name);
                                                deviceBean.setName(name);
                                            }
                                            jParams.put("address", deviceBean.getAddress());
                                            jParams.put("place", aquariumBean.getId());
                                            deviceBean.setPlace(aquariumBean.getId());
                                            Thread.sleep(1000);
                                            int devicetype = deviceBean.getFunctype();
                                            if (devicetype == DeviceConstant.FUNCTYPE_FEEDER || devicetype == DeviceConstant.FUNCTYPE_SWITCH || devicetype == DeviceConstant.FUNCTYPE_PH ||
                                                    devicetype == DeviceConstant.FUNCTYPE_TEMPERATURE ||
                                                    devicetype == DeviceConstant.FUNCTYPE_WATERLEVER) {
                                                DeviceManager.getInstance().Update(connectionEntity, jParams.toString(), new DeviceManager.UpdateCallBack() {
                                                    @Override
                                                    public void onUpdateResponseCallBack(int ret) {
                                                        if (ret == 0) {
                                                            if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_FEEDER || deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_SWITCH || deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_PH || deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_WATERLEVER || deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_TEMPERATURE) {
                                                                if (!aquariumBean.getDeivices().contains(deviceBean.getAddress()))
                                                                    aquariumBean.getDeivices().add(deviceBean.getAddress());
                                                            }
                                                        }
                                                    }
                                                });
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }).start();
                        } else if (operate.equals("Excluded") && SystemConstant.isExcluding) {
                            //删除模式中
                            for (int j = 0; j < SystemConstant.aquariumList.size(); j++) {
                                AquariumBean aquariumBean = SystemConstant.aquariumList.get(j);
                                ArrayList<String> addresses = aquariumBean.getDeivices();
                                for (int i = 0; i < addresses.size(); i++) {
                                    if (addresses.get(i).contains(preRemoveAddress)) {
                                        addresses.remove(i);
                                        --i;
                                    }
                                }
                            }
                            SystemConstant.ruleList = null;
                            SystemConstant.sceneList = null;
                            mHandler.sendEmptyMessage(7);
                        } else if (operate.equals("Excluded") && SystemConstant.isIncluding) {
                            //添加模式中的第一步删除操作
                            for (int j = 0; j < SystemConstant.aquariumList.size(); j++) {
                                AquariumBean aquariumBean = SystemConstant.aquariumList.get(j);
                                ArrayList<String> addresses = aquariumBean.getDeivices();
                                for (int i = 0; i < addresses.size(); i++) {
                                    if (addresses.get(i).contains(preRemoveAddress)) {
                                        addresses.remove(i);
                                        --i;
                                    }
                                }
                            }
                            mHandler.sendEmptyMessageDelayed(13, 3000);
                        } else if (operate.equals("Excluded") && SystemConstant.isRemoveFailedNode) {
                            //删除模式的删除失败节点设置
                            for (int j = 0; j < SystemConstant.aquariumList.size(); j++) {
                                AquariumBean aquariumBean = SystemConstant.aquariumList.get(j);
                                ArrayList<String> addresses = aquariumBean.getDeivices();
                                for (int i = 0; i < addresses.size(); i++) {
                                    if (addresses.get(i).contains(preRemoveAddress)) {
                                        addresses.remove(i);
                                        --i;
                                    }
                                }
                            }
                            SystemConstant.isRemoveFailedNode = false;
                            SystemConstant.ruleList = null;
                            SystemConstant.sceneList = null;
                            mHandler.sendEmptyMessage(7);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case SystemConstant.EVENT_ID_DEVICE_UPGRADE_DOWNLOAD_PERCENTAGE:
                    //固件更新进度通知
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(message);
                        String Strpercent = jsonObject.getJSONObject("data").getString("percentage");
                        int percent = Integer.valueOf(Strpercent);
                        if (HubSettingActivity.getHandler() != null) {
                            Message msg = HubSettingActivity.getHandler().obtainMessage();
                            msg.what = 3;
                            msg.arg1 = percent;
                            HubSettingActivity.getHandler().sendMessage(msg);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case SystemConstant.EVENT_ID_DEVICE_UPGRADE_MD5:
//                    固件升级的MD5通知
                    JSONObject jsonObjectMd5 = null;
                    try {
                        jsonObjectMd5 = new JSONObject(message);
                        String md5MatchResult = jsonObjectMd5.getJSONObject("data").getString("md5");
                        if (HubSettingActivity.getHandler() != null) {
                            Message msg = HubSettingActivity.getHandler().obtainMessage();
                            msg.what = 4;
                            msg.obj = md5MatchResult;
                            HubSettingActivity.getHandler().sendMessage(msg);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case SystemConstant.EVENT_ID_DEVICE_UPGRADE_REBOOT:
                    //固件升级重启通知
                    mHandler.sendEmptyMessage(UPDATING);
                    break;
            }
        }
    }

    //重启对话框
    private void showReboot() {
        final CustomsizeDialog customsizeDialog = new CustomsizeDialog(this);
        customsizeDialog.setTitle(R.string.dialog_title_alert);
        customsizeDialog.setCancelable(false);
        customsizeDialog.setContent(getString(R.string.activity_box_detail_reboot_soon));
        customsizeDialog.setPositiveButton(R.string.sure, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customsizeDialog.dismiss();
                disConnect();
                exit();
            }
        });
        customsizeDialog.show();
    }

    //显示设备报警对话框
    private void showAlarmDialog(final DeviceBean deviceBean) {
        if (alarmDialog == null) {
            alarmDialog = new CustomsizeDialog(this);
            alarmDialog.setTitle(getString(R.string.dialog_title_alert));
            alarmDialog.setPositiveButton(getString(R.string.sure), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alarmDialog.dismiss();
                }
            });
        }
        if (alarmDialog.isShowing()) {
            return;
        }

        if (deviceBean.getAddress().contains("/50/") && deviceBean.getAddress().contains("/2")) {
            //Meter W
            String slist[] = deviceBean.getAddress().split("\\/");
            String switchDeviceBeanAddress = slist[0] + "//" + slist[2] + "/" + slist[3] + "/" + 37 + "/" + slist[5] + "/" + 0; // zwave://e5a00bee/3/37/0/0
            DeviceBean switcDeviceBean = SystemConstant.deviceBeanHashMap.get(switchDeviceBeanAddress);

            if (switcDeviceBean.getSensorvalue() == 255) {
                alarmDialog.setContent(switcDeviceBean.getName() + getString(R.string.str_watt) + " " + getString(R.string.activity_box_detail_dialog_alarm));
                alarmDialog.show();
            }
        } else {
            alarmDialog.setContent(deviceBean.getName() + getString(R.string.activity_box_detail_dialog_alarm));
            alarmDialog.show();
        }


    }

    //刷新设备管理界面
    private void reFreshDeviceManagerFragment() {
        BoxDetailManagerFragment fragment;
        FragmentManager fm = getSupportFragmentManager();
        fragment = (BoxDetailManagerFragment) fm.findFragmentByTag("Manager");
        fragment.onResume();
    }

    //隐藏添加设备对话框
    private void hideDeviceDialog() {
        if (deviceDialog != null)
            deviceDialog.dismiss();
    }

    //退出添加删除模式对话框
    private void initAbortModeDialog() {
//        abortModeDialog = new AlreadyInIncludingDialog(BoxDetailActivity.this);
//        tv_content = (TextView) abortModeDialog.findViewById(R.id.tv_content);
//        bt_positive = (Button) abortModeDialog.findViewById(R.id.bt_positive);
//        bt_positive.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                DeviceManager.getInstance().AbortInclusionExclusion(connectionEntity);
//                abortModeDialog.dismiss();
//            }
//        });
//        abortModeDialog.setCanceledOnTouchOutside(false);
    }

    //{"type":"req","method":"ZWaveController.Reset","callid":1333446400,"params":{},"to":"device_core","source":"2f68f7370a66fb78"}
//{\"type\":\"req\",\"method\":\"Connection.Ping\",\"params\":{\"clientid\":\"%@\"},\"to\":\"device_core\",\"callid\":%@,\"source\":\"%@\"}
    //获取数据
    private void getData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
//                NotifyManager.getInstance().DebugOpen(connectionEntity);
                //获取所有的鱼缸信息  Place 就是鱼缸
                PlaceManager.getInstance().List(connectionEntity, 10);
                //获取所有的设备信息
                DeviceManager.getInstance().List(connectionEntity, 20);
                //获取所有的摄像头信息
                CameraManager.getInstance().List(connectionEntity, 30);
                //获取所有的规则信息
                RuleManager.getInstance().List(connectionEntity, new RuleManager.ListCallBack() {
                    @Override
                    public void onListResponseCallBack(int ret, ArrayList<Object> childList) {
                        if (ret == 0) {
                            SystemConstant.ruleList = childList;
                        }
                    }
                }, 40);

                SystemManager.getInstance().GetUserData(connectionEntity, 100);

                //获取板子时区
                SystemManager.getInstance().GetTimeZone(connectionEntity, new SystemManager.GetTimeZone() {
                    @Override
                    public void onGetTimeZoneCallBack(String result) {
                        if (TextUtils.isEmpty(result)) {
                            connectionEntity.isConnect = true;
                            mHandler.sendEmptyMessage(0);
                            return;
                        }
                        String hubTimezone = null;
                        try {
                            hubTimezone = new JSONObject(result).getString("time_zone");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        hubTimezone = hubTimezone.trim().toString();
                        if (hubTimezone.equals("UTC")) {
                            String appTimeZone = TimeZoneUntil.getTimeZone();
                            if (appTimeZone.contains("+")) {
                                appTimeZone = appTimeZone.replace("+", "-");
                            } else if (appTimeZone.contains("-")) {
                                appTimeZone = appTimeZone.replace("-", "+");
                            } else {
                                appTimeZone = "GTM-8:00";
                            }
                            final String finalAppTimeZone = appTimeZone;
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    JSONObject jsonObject = new JSONObject();
                                    try {
                                        jsonObject.put("time_zone", finalAppTimeZone);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    SystemManager.getInstance().SetTimeZone(connectionEntity, jsonObject.toString(), new SystemManager.SetTimeZone() {
                                        @Override
                                        public void onSetTimeZoneCallBack(String result) {
                                            mHandler.sendEmptyMessage(1008);
                                        }
                                    });

                                    connectingDialog = null;
                                }
                            }).start();
                        } else {
                            connectionEntity.isConnect = true;
                            mHandler.sendEmptyMessage(0);
                        }
                    }
                });
//                P2PTunnelManager.getInstance().sendTest(connectionEntity);
                connectionEntity.ableCheck();
            }
        }).start();
    }

    /**
     * 添加设备显示对话框
     *
     * @param context
     * @param msg
     */
    private void showDeviceDialog(final Context context, String msg) {
        if (deviceDialog == null) {
            deviceDialog = new DetailLoadingDialog(context, R.style.dialog);
            deviceDialog.setCanceledOnTouchOutside(false);//
        }
        deviceDialog.setNegativeButton(getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deviceDialog.dismiss();
                DeviceManager.getInstance().AbortInclusionExclusion(connectionEntity);
                SystemConstant.isIncluding = false;
                SystemConstant.isExcluding = false;
                SystemConstant.excludedCount = 0;
                reFreshDeviceManagerFragment();
            }
        });
        deviceDialog.setTimerOver(new DetailLoadingDialog.TimerOver() {
            @Override
            public void onTimerOver() {
                //倒计时结束
                dialogActionErrorAlert(context);
            }
        });
        deviceDialog.setTitle(msg);
        deviceDialog.show();
    }

    //倒计时结束后弹出的提示对话框
    private void dialogActionErrorAlert(Context context) {
        final CustomsizeDialog customsizeDialog = new CustomsizeDialog(context);
        customsizeDialog.setCancelable(false);
        customsizeDialog.setCanceledOnTouchOutside(false);
        customsizeDialog.setTitle(getString(R.string.dialog_title_alert));
        customsizeDialog.setContent(getString(R.string.dialog_action_error));
        customsizeDialog.setPositiveButton(getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DeviceManager.getInstance().AbortInclusionExclusion(connectionEntity);
                SystemConstant.isIncluding = false;
                SystemConstant.isExcluding = false;
                SystemConstant.excludedCount = 0;
                reFreshDeviceManagerFragment();
                customsizeDialog.dismiss();
            }
        });
        customsizeDialog.show();
    }

    /**
     * 显示连接对话框
     *
     * @param context
     * @param msg
     */
    public void showConnectDialog(Context context, String msg) {
        if (connectingDialog == null) {
            connectingDialog = new DetailLoadingDialog(context, R.style.dialog);
            connectingDialog.setCanceledOnTouchOutside(false);//
        }
        connectingDialog.setNegativeButton(getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                connectingDialog.dismiss();
                disConnect();
                connectionEntity.isConnect = false;
                System.gc();
                isCancel = true;
                SystemConstant.isRunning = false;
                SystemConstant.ruleList = null;
                SystemConstant.sceneList = null;
                SystemConstant.scheduleList = null;
                DeviceConstant.alarmConditionBeanHashMap = null;
                exit();
            }
        });
        connectingDialog.setTitle(msg);
        connectingDialog.show();
    }

    /**
     * 隐藏连接对话框
     */
    public void hideConnectDialog() {
        if (connectingDialog != null) {
            connectingDialog.dismiss();
        }
    }

    public void changeConnectDialog(Context context, int titleId) {
        if (connectingDialog == null) {
            connectingDialog = new DetailLoadingDialog(context, R.style.dialog);
            connectingDialog.setCanceledOnTouchOutside(false);//
        }
        connectingDialog.changeTitle(titleId);
    }

    /**
     * 改变连接对话框中显示的文本
     *
     * @param context
     * @param msg
     */
    public void changeConnectDialog(Context context, String msg) {
        if (connectingDialog == null) {
            connectingDialog = new DetailLoadingDialog(context, R.style.dialog);
            connectingDialog.setCanceledOnTouchOutside(false);//
        }
        connectingDialog.changeTitle(msg);
    }

    private void showMessageWaitingDialog(Context context, String message) {
        if (messageWaitingDialog == null)
            messageWaitingDialog = new CustomsizeDialog(context);
        messageWaitingDialog.setLoadingText(message);
        messageWaitingDialog.show();
    }

    //隐藏等待的对话框
    private void hideMessageWaitingDialog() {
        if (messageWaitingDialog != null)
            messageWaitingDialog.dismiss();
    }

    /**
     * 显示连接失败的对话框
     *
     * @param context
     * @param msg     显示的内容
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public void showConnectErrorDialog(Context context, String msg) {
        if (BoxDetailActivity.this.isFinishing()) {
            return;
        }
        if (BoxDetailActivity.this.isDestroyed()) {
            return;
        }
        if (connectErrorDialog == null) {
            connectErrorDialog = new CustomsizeDialog(context);
            connectErrorDialog.setTitle(getString(R.string.dialog_title_alert));
            connectErrorDialog.setCancelable(false);
        }
        connectErrorDialog.setContent(msg);
        connectErrorDialog.setPositiveButton(getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                connectErrorDialog.dismiss();
                disConnect();
                exit();
            }
        });
        connectErrorDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        orientationEventListener.disable();
        disConnect();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    class UiHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1003:
                    //原来P2P的连接参数配置
                    break;
                case 1004:
                    //连接成功
                    getData();
                    SharedUtil.getInstance().writeLastConnect(currentBoxBean.getUid());
                    break;
                case 1005:
                    //手机号密码错误
                    hideConnectDialog();
                    showConnectErrorDialog(BoxDetailActivity.this, getString(R.string.activity_box_detail_username_error));
                    break;
                case 1006:
                    //断开连接
                    hideConnectDialog();
                    showConnectErrorDialog(BoxDetailActivity.this, getString(R.string.activity_box_detail_disconnect));
                    break;
                case 1007:
                    //切换连接
                    if (connectErrorDialog != null) {
                        if (connectErrorDialog.isShowing()) {
                            connectErrorDialog.dismiss();
                        }
                    }
                    showConnectDialog(BoxDetailActivity.this, getString(R.string.activity_box_detail_reconnect));
                    break;
                case 1008:
                    //首次连接设置时区
                    showConnectErrorDialog(BoxDetailActivity.this, getString(R.string.activity_box_detail_settimezone));
                    break;
//************************************************UI逻辑********************************************************************************
                case 0:
                    //初始化实时界面
                    resetBottomMenuStatus(menuIndex);
                    menuIndex = -1;
                    lastIndex = 0;
                    SystemConstant.ruleList = null;
                    SystemConstant.sceneList = null;
                    SystemConstant.scheduleList = null;
                    setDefaultFragment();
                    hideConnectDialog();
                    break;
                case SWITCHCURRENTFRAGMENT:
                    //切换到CurrentFragment
                    AquariumBean aquariumBeans = null;
                    aquariumBeans = (AquariumBean) msg.obj;
                    SystemConstant.currentAquariumBean = aquariumBeans;
                    resetBottomMenuStatus(4);
                    switchCurrentFragment(aquariumBeans);
                    int position = msg.arg1;
                    menuItemAdapter.setHighLightIndex(position + 1);
                    break;
                case LEFTMENUITEMUPDATE:
                    //刷新左侧菜单鱼缸界面
                    menuItemAdapter.creatAquariumMenu();
                    hideMessageWaitingDialog();
                    break;
                case 3:
                    //弹出拨三下的  对话框
                    if (SystemConstant.excludedCount == 0) {
                        BoxDetailManagerFragment fragment;
                        FragmentManager fm = getSupportFragmentManager();
                        fragment = (BoxDetailManagerFragment) fm.findFragmentByTag("Manager");
                        fragment.hideLoadingDialog();
                        showDeviceDialog(BoxDetailActivity.this, getString(R.string.activity_box_detail_add_first));
                    }
                    break;
                case 4:
                    //改变添加对话框的title
                    if (SystemConstant.isIncluding)
                        deviceDialog.changeTitle(getString(R.string.activity_box_detail_dialog_adding));
                    if (SystemConstant.isExcluding)
                        deviceDialog.changeTitle(getString(R.string.activity_box_detail_deleting));
                    break;
                case 5:
                    //弹出倒计时结束 退出模式的对话框
                    hideConnectDialog();
                    hideLoadingDialog();
                    initAbortModeDialog();
                    if (abortModeDialog != null)
                        abortModeDialog.show();
                    break;
                case 6:
                    //添加设备成功
                    hideDeviceDialog();
                    showToast(getString(R.string.add_device_success));
                    //添加状态标志 恢复
                    SystemConstant.isIncluding = false;
                    SystemConstant.includingDeviceNum = 0;
                    SystemConstant.excludedCount = 0;
//                    preAddDeviceArray=null;
                    //刷新设备管理界面
                    reFreshDeviceManagerFragment();
                    break;
                case 7:
                    //删除设备成功
                    hideDeviceDialog();
                    hideloadingDialog();
                    showToast(getString(R.string.remove_device_success));
                    //删除状态标志 恢复
                    SystemConstant.isExcluding = false;
                    //刷新设备管理界面
                    reFreshDeviceManagerFragment();
                    break;
                case 8:
                    //更新实时界面
                    BoxDetailCurrentFragment currentFragment;
                    FragmentManager currentfm = getSupportFragmentManager();
                    currentFragment = (BoxDetailCurrentFragment) currentfm.findFragmentByTag("Current");
                    if (currentFragment != null) {
                        currentFragment.update();
                    }
                    break;
                case 9:
                    //在所有鱼缸界面时，更新所有鱼缸数据
                    BoxDetailAllFragment allFragment;
                    FragmentManager allfm = getSupportFragmentManager();
                    allFragment = (BoxDetailAllFragment) allfm.findFragmentByTag("All");
                    if (allFragment != null) {
                        allFragment.updateData();
                    }
                    break;
                case 10:
//                    跳转到更多界面并重置底部菜单
                    resetBottomMenuStatus(menuIndex);
                    switchMoreFragment(aquariumBean);
                    break;
                case 11:
                    String text = (String) msg.obj;
                    showMessageWaitingDialog(BoxDetailActivity.this, text);
                    break;
                case 12:
                    //隐藏添加设备的对话框
                    hideDeviceDialog();
                    break;
                case 13:
                    //再一次拨三下，弹出对话框
                    if (SystemConstant.isIncluding) {
                        if (deviceDialog != null) {
                            deviceDialog.changeTitle(getString(R.string.activity_box_detail_add_second));
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    DeviceManager.getInstance().StartInclude(connectionEntity);
                                }
                            }).start();
                        }
                    }
                    break;
                case 14:
                    //重置
                    if (deviceDialog != null)
                        deviceDialog.changeTitle(getString(R.string.activity_box_detail_reset));
                    break;
                case COUNTDOWN:
                    //如果消息发送出去后么有收到结果，判定认为断开连接
                    hideConnectDialog();
                    String callid = (String) msg.obj;
                    if (connectionEntity.countdowns != null) {
                        if (connectionEntity.countdowns.contains(callid)) {
                            hideloadingDialog();
                            showConnectErrorDialog(BoxDetailActivity.this, getString(R.string.dialog_content_disconnect));
                        } else {
//                            System.out.println("成功接收");
                        }
                    } else {
                        hideloadingDialog();
                        showConnectErrorDialog(BoxDetailActivity.this, getString(R.string.dialog_content_disconnect));
                    }
                    break;
                case ALARM:
                    //设备报警弹窗
                {
                    DeviceBean deviceBean = (DeviceBean) msg.obj;
                    showAlarmDialog(deviceBean);
                    break;
                }
                case ALARM_RECOMPUTER: {
                    final DeviceBean wattBean = (DeviceBean) msg.obj;
                    String slist[] = wattBean.getAddress().split("\\/");
                    String switchAddress = slist[0] + "//" + slist[2] + "/" + slist[3] + "/" + 37 + "/" + slist[5] + "/" + 0; // zwave://e5a00bee/3/50/3/2
                    DeviceBean switchBean = SystemConstant.deviceBeanHashMap.get(switchAddress);

                    if (switchBean != null && switchBean.getSensorvalue() == 255 && wattBean.getSensorvalue() < 10 && wattBean.getSensorvalue() >= 0) {
                        //to check switch
                        wattBean.oldAlarmType = 8;

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showAlarmDialog(wattBean);
                            }
                        });
                    } else {
                        wattBean.oldAlarmType = 0;
                    }

                    //更新实时界面
                    BoxDetailCurrentFragment currentFragment2;
                    FragmentManager currentfm2 = getSupportFragmentManager();
                    currentFragment2 = (BoxDetailCurrentFragment) currentfm2.findFragmentByTag("Current");
                    if (currentFragment2 != null) {
                        currentFragment2.update();
                    }

                    System.out.println("switchBean.getSensorvalue()=" + switchBean.getSensorvalue());
                    System.out.println("wattBean.getSensorvalue()=" + wattBean.getSensorvalue());
                    System.out.println("ALARM_RECOMPUTER, wattBean.oldAlarmType=" + wattBean.oldAlarmType);
                    break;
                }

                case UPDATING:
                    //固件更新重启
                    showReboot();
                    break;
                case REMOVEFAILED:
                    //删除失败节点
                    if (SystemConstant.isRemoveFailedNode) {
                        hideDeviceDialog();
                        hideloadingDialog();
                        showLongToast(getString(R.string.activity_box_detail_delete_failed));
                        SystemConstant.isRemoveFailedNode = false;
                        reFreshDeviceManagerFragment();
                    }
                    break;
            }
        }
    }
}
